package cn.wolfcode.interceptor;

import cn.wolfcode.domain.Result;
import cn.wolfcode.utils.JwtUtils;
import com.alibaba.fastjson.JSON;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        try {
            JwtUtils.parseJwt(token);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            response.setContentType("application/json;charset=utf-8");
            Result notLogin = Result.error("NOT_LOGIN");
            //这只是对象不是json字符 需要把对象转换成json字符串来响
            //不是controller 需要手动响应 controller是自动响应 返回一个Result对象即可
            String jsonString = JSON.toJSONString(notLogin);
            response.getWriter().write(jsonString);
            return false;
        }



    }
}
